$(function () {
    layui.use(['element', 'form', 'table', 'laytpl', 'layer', 'util'], function () {
        var table = layui.table,
            element = layui.element,
            form = layui.form,
            layer = layui.layer,
            $ = layui.$,
            util = layui.util,
            laytpl = layui.laytpl;
        //渲染表格
        var categories = {};
        var goods  = {};

        $.ajax({
            url: "category.json",
            async: false,
            dataType: "json",
            success: function (data) {
                categories = data;
            }
        });

        form.render();
        table.render({
            elem: '#table',
            url: '/api/goods/list',
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'goodsId', sort: true, title: '商品编号', minWidth: '70'},
                {field: 'goodsName', sort: true, title: '名称', minWidth: '200'},

                {
                    field: 'src', sort: true, title: '图片描述',
                    templet: function (d) {
                        var prefix = localStorage.getItem("prefix");
                        var src = d.src;
                        src = (prefix.toString()+src);
                        return '<div><img src="'+src.substring(0,src.length-1)+'" style="height:150px;width:150px;"</div>';
                    },
                    minWidth: '120',
                    event:'previewPic'
                },
                {field: 'price', sort: true, title: '价格'},
                {field: 'category', sort: true, title: '种类'},
                {field: 'userName', sort: true, title: '发布者'},
                {field: 'phone', sort: true, title: '联系方式'},
                {field: 'location', sort: true, title: '交易地址'},

                {
                    field: 'createTime', sort: true, templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, title: '发布时间'
                },
                {align: 'center', toolbar: '#barTpl', minWidth: 80, title: '操作'}
            ]]
        });

        //添加按钮点击事件
        $("#addBtn").click(function () {
            showEditModel(null);
        });

        //表单提交事件
        form.on('submit(btnSubmit)', function (data) {
            var type = $("#editForm").attr("method");
            if (type === "PUT") {
                data.field.timeModified = util.toDateString(util.toDateString(new Date()));
            }
            layer.load(1);

            $.ajax({
                url: "/api/goods/",
                type: type,
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(data.field),
                dataType: "json",
                success: function (data) {
                    layer.closeAll('loading');
                    if (data.code === 0) {
                        layer.msg(data.msg, {icon: 1});
                        layer.closeAll('page');
                        table.reload('table', {});
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }
            });
            return false;
        });

        //工具条点击事件
        table.on('tool(table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { //修改
                showEditModel(data);
            } else if (layEvent === 'previewPic') { //预览
                var prefix = localStorage.getItem("prefix");
                var src = data.src;
                src = (prefix.toString()+src);
                var content = '<div><img src="'+src.substring(0,src.length-1)+'" style="height:500px;width:500px;"</div>';
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    area: 'auto',
                    skin: 'layui-layer-nobg', //没有背景色
                    shadeClose: true,
                    content: content
                });
            } else {
            }
        });



        //搜索按钮点击事件
        $("#searchBtn").click(function () {
            doSearch(table);
        });


//显示表单弹窗
        function showEditModel(data) {
            layer.open({
                type: 1,
                title: data == null ? "添加商品" : "修改商品",
                area: '400px',
                offset: '120px',
                content: $("#addModel").html()
            });
            $("#editForm")[0].reset();
            $("#editForm").attr("method", "POST");
            form.on('select(school-filter)', function (data) {
                form.render();
            });
            var selectItem = data.category;
            if (data != null) {
                renderSelectCategory(selectItem);
                $("#editForm input[name=id]").val(data.goodsId);
                $("#editForm input[name=name]").val(data.goodsName);
                // $("#editForm input[id=selCategory]").val(data.category);
                $("#editForm input[name=price]").val(data.price);
                $("#editForm input[name=location]").val(data.location);
                //$("#editForm input[name=campus]").val(data.campus);
                $("#editForm").attr("method", "PUT");

                form.render('radio');

            }
            $("#btnCancel").click(function () {
                layer.closeAll();
            });
        }


//搜索
        function doSearch(table) {
            var key = $("#searchKey").val();
            var value = $("#searchValue").val();
            if (value === '') {
                key = '';
            }
            table.reload('table', {where: {searchKey: key, searchValue: value}});
        }

        function renderSelectCategory(selectedItem) {
            var getTpl = selectCategoryTpl.innerHTML,
                view = document.getElementById('selCategory');
            laytpl(getTpl).render(categories, function (html) {
                view.innerHTML = html;
                view.value = (selectedItem);
            });
        }
    });


});
